package com.oppodowngrader;

import android.content.Context;
import android.util.Log;

import org.littleshoot.proxy.HttpFilters;
import org.littleshoot.proxy.HttpFiltersAdapter;
import org.littleshoot.proxy.HttpFiltersSourceAdapter;
import org.littleshoot.proxy.HttpProxyServer;
import org.littleshoot.proxy.impl.DefaultHttpProxyServer;
import org.littleshoot.proxy.mitm.Authority;
import org.littleshoot.proxy.mitm.CertificateSniffingMitmManager;

import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;

public class ProxyServer {
    private static final String TAG = "ProxyServer";
    private static final int PORT = 8080;
    
    private final Context context;
    private final ConfigManager configManager;
    private final CertificateManager certificateManager;
    private HttpProxyServer server;

    public ProxyServer(Context context) {
        this.context = context;
        this.configManager = new ConfigManager(context);
        this.certificateManager = new CertificateManager(context);
    }

    public void start() {
        try {
            // 获取证书和私钥
            PrivateKey privateKey = certificateManager.getPrivateKey();
            X509Certificate certificate = certificateManager.getCertificate();
            
            if (privateKey == null || certificate == null) {
                throw new RuntimeException("无法获取证书或私钥");
            }
            
            // 创建MITM管理器用于HTTPS拦截
            Authority authority = new Authority(certificate, privateKey);
            CertificateSniffingMitmManager mitmManager = new CertificateSniffingMitmManager(authority);
            
            server = DefaultHttpProxyServer.bootstrap()
                    .withPort(PORT)
                    .withManInTheMiddle(mitmManager)
                    .withFiltersSource(new HttpFiltersSourceAdapter() {
                        @Override
                        public HttpFilters filterRequest(HttpRequest originalRequest) {
                            return new HttpFiltersAdapter(originalRequest) {
                                @Override
                                public HttpResponse clientToProxyRequest(HttpObject httpObject) {
                                    if (httpObject instanceof HttpRequest) {
                                        HttpRequest request = (HttpRequest) httpObject;
                                        String uri = request.uri();
                                        Log.d(TAG, "拦截请求: " + uri);
                                        
                                        // 检查是否是目标URL
                                        String targetUrl = configManager.getTargetUrl();
                                        if (uri.contains(targetUrl) || uri.contains("firmwareInfo")) {
                                            Log.d(TAG, "检测到耳机固件更新请求");
                                            // 直接返回我们的自定义响应，而不是转发请求
                                            return createCustomResponse();
                                        }
                                    }
                                    return null; // 继续正常处理其他请求
                                }
                            };
                        }
                    })
                    .start();
            
            Log.d(TAG, "代理服务器启动成功，端口：" + PORT);
        } catch (Exception e) {
            Log.e(TAG, "启动代理服务器失败", e);
            throw new RuntimeException("无法启动代理服务器", e);
        }
    }
    
    public void stop() {
        if (server != null) {
            server.stop();
            server = null;
            Log.d(TAG, "代理服务器已停止");
        }
    }
    
    private HttpResponse createCustomResponse() {
        // 从配置管理器获取响应内容
        String responseBody = configManager.getResponseBody();
        
        ByteBuf buffer = Unpooled.copiedBuffer(responseBody, StandardCharsets.UTF_8);
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                buffer);
        
        response.headers().set("Content-Type", "application/json; charset=UTF-8");
        response.headers().set("Content-Length", buffer.readableBytes());
        
        Log.d(TAG, "已生成自定义固件响应");
        return response;
    }
}